package com.rsc.learningbar.service;

import com.alibaba.fastjson.JSON;
import com.rsc.learningbar.vo.Plan;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.*;

@Service
@Slf4j
public class PlanNotifyService {
    @Autowired
    @Qualifier("plan-notify")
    ExecutorService threadPoolExecutor;

    @Autowired
    DelayQueue<Plan> delayQueue;

    public void start() {
        threadPoolExecutor.submit(() -> {
            try {
                for (; ; ) {
                    Plan plan = delayQueue.take();
                    Long userId = plan.planVo.getUserId();

                    if (WebSocketPlanService.ONLINE_USER_SESSIONS.containsKey(userId)) {
//                        WebSocketPlanService.sendMessage(WebSocketPlanService.ONLINE_USER_SESSIONS.get(userId), JSON.toJSONString(plan.planVo));
                        WebSocketPlanService.sendMessage(WebSocketPlanService.ONLINE_USER_SESSIONS.get(userId), plan.planVo.getStudentMissionName());
                    } else {
                        // 丢弃，待连接会自动续上
                        log.info("丢弃：" + JSON.toJSONString(plan.planVo));
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
